<?php

/*
  Contiene la classe che gestisce i template del sito
 */
require "include/template2.inc.php";
require "include/user.inc.php";
require "include/common.inc.php";
require "include/db_manager.inc.php";
require_once 'include/language_manager.inc.php';

Class Template_Manager {

    private $main;
    private $body;
    private $user;
    private $menu;
    private $menuLastIndex = 10;
    private $success;
    private $allowed;
    private $error;
    private $closed = false;

    /**
     * 
     * @param type $title Titolo della pagina
     * @param type $mask Maschera che realizza la pagina  
     * @param type $role Array contente i ruoli 
     * @param type $autoredirect Indica se in caso di autorizzazione negata bisogna chiamare l'autoridirezione
     * @param type $menu Permette di specificare un menu particlare per la pagina
     * @param type $success Permette di specificare il placeholder del success 
     * @param type $error Permette di specificare il placeholder dell'errore
     */
    public function __construct($mask, $role = null, $autoredirect = true, $sel = null, $meta = null, $success = "successmessage", $error = "errormessage") {
        $this->allowed = false;
        $this->success = $success;
        $this->error = $error;
        $this->setHeader($meta);
        session_start();
        $this->setUser();
        if ($this->auth($role)) {
            $this->setBody($mask);
            $this->setMenu($sel);
            /* foreach ($sidebar as $key => $value) {
              $this->setSectionContent($this->body, $key, $sidebar);
              } */
            //$this->setLoginUserVariable();
            $this->setLastOperation();
        } else {
            if ($autoredirect)
                redirect();
        }
        $this->setSectionContentSponsor();
        $this->addGoogleCode();
    }
    
    protected function addGoogleCode() {
        require_once 'include/language_manager.inc.php';
        Language_Manager::getInstance();
        if (getLanguage() == 'en') {
            $this->main->setContent("ga_code_only_en", L::ga_code_only_en);
        } else {
            $this->main->setContent("ga_code_only_en", "");
        }
    }

    public function __destruct() {
        if (!$this->closed)
            $this->exec();
    }

    public function getMain() {
        return $this->main;
    }

    public function getBody() {
        return $this->body;
    }

    public function getUser() {
        return $this->user;
    }

    public function getMenu() {
        return $this->menu;
    }

    public function setMenu($sel = 1) {
        Language_Manager::getInstance();
        $prefix = "";
        if (getLanguage() == 'en') {
            $this->menu = new Template(Config::$site_skin . "menu_en.html");
            $prefix = "/en";
        } else {
            $this->menu = new Template(Config::$site_skin . "menu.html");
        }
        
        for ($i = 1; $i <= $sel; $i++) {
            $this->menu->setContent("menu" . $sel, "id=\"current\"");
        }
        $this->menu->setContent("menu" . $sel, "id=\"current\"");
        for ($i = $sel + 1; $i <= $this->menuLastIndex; $i++) {
            $this->menu->setContent("menu" . $sel, "id=\"current\"");
        }
        
        $this->main->setContent("contacts", L::url_contacts);
        $this->main->setContent("title_contacts", L::title_contacts);
        $this->main->setContent("contact_us", L::title_contact_us);
        $this->main->setContent("title_authors", L::title_authors);
        $this->main->setContent("nav_footer_home", L::nav_footer_home);
        $this->main->setContent("nav_authors", L::nav_authors);
        $this->main->setContent("nav_apply", L::nav_apply);
        
        $this->menu->setContent("menu_home", L::menu_home);
        $this->menu->setContent("menu_master", L::menu_master);
        $this->menu->setContent("menu_subscribe", L::menu_subscribe);
        $this->menu->setContent("menu_contact", L::menu_contact);
        $this->menu->setContent("menu_faq", L::menu_faq);
        $this->menu->setContent("menu_recipe", L::menu_recipe);
        $this->menu->setContent("menu_news", L::menu_news);
        $this->menu->setContent("menu_vips", L::menu_vips);
        $this->menu->setContent("menu_news", L::menu_news);
        $this->menu->setContent("menu_wines", L::menu_wines);
        $this->menu->setContent("site_name", Config::$site_name . $prefix);
        
        $this->main->setContent("menu", $this->menu->get());
    }

    public function setLoginUserVariable($tuplaUtente) {
        
    }

    private function setHeader($meta) {
        //setLastOperation();
        /* main template declaration */

        $value = new Template(Config::$site_skin . "frame.html");
        $this->main = $value;
        if ($meta) {
            $this->setMeta($meta);
        }
        $this->main->setContent("logo", Config::$site_upload . "MasterInCucina.png");

        Language_Manager::getInstance();
        $this->main->setContent("header_static", L::header);
        $this->main->setContent("master_current", L::master_current);
        $this->main->setContent("master_school", L::master_school);
        $this->main->setContent("master_subscribe", L::master_subscribe);

        $this->main->setContent("nav_home", L::nav_home);
        $this->main->setContent("nav_contact", L::nav_contact);
        $this->main->setContent("nav_who", L::nav_who);
    }

    public function setMeta($meta) {
        $this->main->setContent("title", $meta["title"]);
        $this->main->setContent("meta_description", $meta["description"]);
        $this->main->setContent("meta_keywords", $meta["keywords"]);
        $this->main->setContent("site_name", Config::$site_name);
    }

    public function isAllowed() {
        return $this->allowed;
    }

    private function auth($roles) {
        if ($roles != null) {
            if ($this->user) {
                foreach ($roles as $key => $role) {
                    if ($this->user->getGroup() == $role) {
                        $this->allowed = true;
                        break;
                    }
                }
            }
        } else {
            $this->allowed = true;
        }
        return $this->allowed;
    }

    private function setUser() {
        if (isset($_SESSION['user'])) {
            $this->user = unserialize($_SESSION['user']);
        } else {
            $this->user = false;
        }
        if ($this->user) {
            $this->setSectionContentString($this->main, "login_button", 'Benvenuto <a href="user-page.php">'
                    . $this->user->getUsername() . '</a>&nbsp&nbsp<a id="logout" href="logout.php" class="button grey small circle">logout</a>');
        } else {
            $this->setSectionContentString($this->main, "login_button", '<a id="login" href="login.php" class="button grey small circle">login</a>');
        }
    }

    private function setBody($skinPage) {
        $this->body = new Template(getSkinPath() . $skinPage . ".html");
    }

    /**
     * Prende una sezione $section trova l'etichetta $content e la rimpiazza col
     * $mask 
     * @param type $section sezione che contiene il placeholder
     * @param type $content placeholder da riempire
     * @param type $mask contenuto utilizzato per riempire
     */
    public function setSectionContent($section, $content, $mask) {
        $section->setContent($content, (new Template(Config::$site_skin . $skinPage . ".html"))->get());
    }

    /**
     * Prende una sezione $section trova l'etichetta $content e la rimpiazza col
     * contenuto $string
     * @param type $section sezione che contiene il placeholder
     * @param type $content placeholder da riempire
     * @param type $string contenuto utilizzato per riempire
     */
    public function setSectionContentString($section, $content, $string = NULL) {
        if ($string == NULL) {
            $section->setContent($content);
        } else {
            $section->setContent($content, $string);
        }
    }

    /**
     * Prende una sezione $section trova l'etichetta $content e la rimpiazza col
     * url di un immagine
     * @param type $section sezione che contiene il placeholder
     * @param type $content placeholder da riempire
     * @param type $imageURL url dell'immagine
     */
    public function setSectionContentImage($section, $content, $imageURL) {
        $section->setContent($content, Config::$site_upload . $imageURL);
    }

    /**
     * Effettua upload dal sito
     * @param type $file descrittore del file da cancellare
     * @param type $type folder di destinazione sotto la cartella uploads
     * @param type $verify condizioni di verifica file
     */
    public function upload($file, $type, $verify) {
        if ($verify) {
            if (($verify["error"]) && ($file["error"] > 0))
                return null;
            if (($verify["size"]) && ($file["size"] > 1024000))
                return null;
            if (($verify["ext"]) && ($verify["ext"][pathinfo($file["name"], PATHINFO_EXTENSION)] == null))
                return null;
        }
        $dest = $type . "/" . $file["name"];
        if (file_exists(Config::$site_upload . $dest)) {
            $dest = $type . "/" . pathinfo($file["name"], PATHINFO_FILENAME) . "_" . date("YmdHis") . "." . pathinfo($file["name"], PATHINFO_EXTENSION);
        }
        $file["name"] = $dest;
        $pippo = Config::$site_upload . $dest;
        if (!move_uploaded_file($file["tmp_name"], Config::$site_upload . $dest))
            $file["size"] = 0;
        return $file;
    }

    /**
     * Effettua cancellazione di un file
     * @param type $verify condizioni di verifica file
     */
    public function deletefile($filename) {
        return unlink(Config::$site_upload . $filename);
    }

    /**
     * Prende una sezione $section trova l'etichetta $content e la rimpiazza col
     * url di un immagine
     * @param type $section sezione che contiene il placeholder
     * @param type $content placeholder da riempire
     *
     */
    public function setBodyContent($content, $skinPage = NULL) {
        if ($skinPage == NULL) {
            $this->body->setContent($content);
        } else {
            $this->body->setContent($content, (new Template(Config::$site_skin . $skinPage . ".html"))->get());
        }
    }

    /**
     * Prende una sezione $section trova l'etichetta $content e la rimpiazza col
     * url di un immagine
     * @param type $section sezione che contiene il placeholder
     * @param type $template il template da andare ad inserire nel placeholder
     *
     */
    public function setBodyTemplate($content, $template) {
        $this->body->setContent($content, $template->get());
    }

    /**
     * trova l'etichetta $content nel $body e la rimpiazza col
     * contenuto $string
     * @param type $content placeholder da riempire
     * @param type $string contenuto utilizzato per riempire
     */
    public function setBodyContentString($content, $string) {
        $this->body->setContent($content, $string);
    }

    /**
     * trova l'etichetta $content nel $body e la rimpiazza col
     * url di $imageURL
     * @param type $content placeholder da riempire
     * @param type $imageURL url di un'immagine
     */
    public function setBodyContentImage($content, $imageURL) {
        $this->body->setContent($content, Config::$site_name . '/' . Config::$site_upload . $imageURL);
    }

    /**
     * trova l'etichetta di errore nel $body e la rimpiazza col
     * errore preso dal $dbmanager
     * @param type $dbmanager instanza della classe DB_manager che gestisce la
     *                        connessione al DB 
     */
    public function setBodyDBError($dbmanager) {
        $this->body->setContent($this->error, $dbmanager->getCodeError());
    }

    /**
     * trova l'etichetta di errore nel $body e la rimpiazza col
     * errore indicato in $string
     * @param type $string Stringa da inserire nel container di errore 
     */
    public function setBodyError($string) {
        $this->body->setContent($this->error, $string);
    }

    /**
     * trova l'etichetta di errore nel $body e la rimpiazza col
     * messaggio indicato in $string
     * @param type $string Stringa da inserire nel container di successo 
     */
    public function setBodySuccess($string) {
        $this->body->setContent($this->success, $string);
    }

    /**
     *  Crea la sezione dei Testimonials
     */
    public function setSectionContentTesimonials($section = null) {
        if (!isset($section))
            $section = $this->body;
        $mysqli = DB_Manager::getInstance();
        $sql = 'SELECT * FROM testimonials AS t, users AS u WHERE t.id_user = u.id';

        if ($data = $mysqli->query($sql)) {
            if (mysqli_num_rows($data)) {
                //$row = $data->fetch_array(MYSQLI_ASSOC);
                foreach ($data as $row) {
                    $this->setSectionContentString($section, 'testimonial_name', getCompleteNameById($row['id_user']));
                    $this->setSectionContentString($section, 'testimonial_work', $row['nowWork']);
                    $this->setSectionContentString($section, 'testimonial_text', $row['text']);
                    $this->setSectionContentImage($section, 'testimonial_avatar', getAvatarPathByIdUser($row['id_user']));
                }
            }
        }
    }

    public function setSectionContentSponsor() {
        $mysqli = DB_Manager::getInstance();
        $sponsor = '';
        $sql = 'select `s`.`id` AS `id`,`i`.`nome` AS `nome`,`i`.`uri` AS `img`,`i`.`descrizione` AS `descrizione`,`i`.`descrizione_en` AS `descrizione_en` from (`sponsor` `s` join `immagine` `i`) where (`s`.`immagine` = `i`.`id`)';
        if ($data = $mysqli->query($sql)) {
            if (mysqli_num_rows($data)) {
                //$row = $data->fetch_array(MYSQLI_ASSOC);
                $i = 0;
                foreach ($data as $row) {
                    $descrizione = "";
                    if (getLanguage() == 'it') {
                        $descrizione = $row['descrizione'];
                    } else {
                        $descrizione = $row['descrizione_en'];
                    }
                    if ($i == 0)
                        $sponsor = $sponsor . '<li>';
                    $sponsor = $sponsor .
                            '<div class="one-fifth">
                         <a href="#" class="tooltip" title="' . $descrizione . '"><img src="' . Config::$site_name . '/' . Config::$site_upload . $row['img'] . '" alt="' . $descrizione . '"/></a>
                     </div>';
                    $i++;
                    if ($i == 5) {
                        $i = 0;
                        $sponsor = $sponsor . '</li>';
                    }
                }
                if ($i != 0) {
                    $sponsor = $sponsor . '</li>';
                }
                setSectionContentString($this->main, 'sponsors', $sponsor);
            }
        }
    }

    public function setSectionContentSlides() {
        $slides = '';
        $mysqli = DB_Manager::getInstance();
        $sql = 'select `s`.`id` AS `id`,`i`.`nome` AS `nome`,`i`.`nome_en` AS `nome_en`,`i`.`uri` AS `img`,`i`.`descrizione` AS `descrizione`,`i`.`descrizione_en` AS `descrizione_en`,`s`.`link` AS `link`,`s`.`link_en` AS `link_en` from (`slides` `s` join `immagine` `i`) where (`s`.`immagine` = `i`.`id`) ';
        if ($data = $mysqli->query($sql)) {
            if (mysqli_num_rows($data)) {
                //$row = $data->fetch_array(MYSQLI_ASSOC);
                foreach ($data as $row) {
                    $descrizione = "";
                    if (getLanguage() == 'it') {
                        $nome = $row['nome'];
                        $descrizione = $row['descrizione'];
                        $btnText = "Per saperne di pi&ugrave;...";
                        $link = $row['link'];
                    } else {
                        $nome = $row['nome_en'];
                        $descrizione = $row['descrizione_en'];
                        $btnText = "Find out more";
                        $link = $row['link_en'];
                    }
                    $slides = $slides .
                            '<div class="ls-layer" style="slidedirection: top; slideoutdirection : left; slidedelay: 5000; durationin: 1500; durationout: 1500; delayout: 500;">
                        <img src="' . Config::$site_name . '/' . Config::$site_upload . 'slide-bg.jpg" class="ls-bg" alt="background">
                        <img src="' . Config::$site_name . '/' . Config::$site_upload . $row['img'] . '" class="ls-s6" alt="' . $nome . '" style="top: 10px; left:550px; slidedirection : bottom; slideoutdirection : bottom; durationin : 1500; durationout : 750; easingin : easeInOutQuint; easingout : easeInOutQuint; delayin : 300;">
                        <h2 class="ls-s3 ls_large_text_01" style="position: absolute; top:100px; left: 0px; slidedirection : top; slideoutdirection : top; durationin : 3000; durationout : 750; easingin : easeInOutQuint; easingout : easeInBack; delayin : 500;">' . $nome . '</h2>
                        <h4 class="ls-s3 l1-s1 ls_large_text_02" style="position: absolute; top:160px; left: 0px; slidedirection : bottom; slideoutdirection : bottom; durationin : 3000; durationout : 750; easingin : easeInOutQuint; easingout : easeInBack; delayin : 600;">' . $descrizione . '</h4>
                        <a class="button huge color round ls-s8" href="' . $link . '" style="position: absolute; top:210px; left: 0px; slidedirection : bottom; slideoutdirection : bottom; durationin : 3000; durationout : 750; easingin : easeInOutQuint; easingout : easeInOutQuint; delayin : 700;">' . $btnText . '</a>
                    </div>';
                }
                $this->setBodyContentString('slides', $slides);
            }
        }
    }

    /**
     *  Genera un ciclo per i gruppi
     */
    public function setSectionContentGroups($requestGroup) {
        $mysqli = DB_Manager::getInstance();
        $group = getGroups($mysqli);
        while ($row = $group->fetch_array(MYSQLI_ASSOC)) {
            $this->setBodyContentString("groupid", $row['id']);
            $this->setBodyContentString("groupname", $row['name']);
            if (isset($requestGroup) && ($requestGroup == $row['id'])) {
                $this->setBodyContentString("groupselected", "selected");
            }
        }
    }

    /**
     *  Genera un ciclo per i gruppi
     */
    public function setCanonicalUrl($url) {
        $canonical = '<link rel="canonical" href="' . Config::$site_name . '/' . $url . '"/>';
        $this->setSectionContentString($this->main, "linkcanonical", $canonical);
    }

    /**
     * se l'utente è loggato 
     * @param type $string Stringa da inserire nel container di successo 
     */
    public function setLastOperation() {
        if (userIsLoggedIn()) {
            $table = "users";
            $set["time_last_operation"] = time();
            $where["id"] = $this->user->getId();
            $query = DB_Manager::queryUpdateEasy($table, $set, $where);
            DB_Manager::getInstance()->query($query);
        }
    }

    public function exec() {
        $this->body->setContent("site_name", Config::$site_name);
        $this->main->setContent("body", $this->body->get());
        $this->main->close();
        $this->closed = true;
    }

}

?>